from core.excel_file import ExcelFile
from core.cell_data_handler import CellDataHandler
from core.condition import Condition


class ExcelHandler(ExcelFile):

    __STYLE_PROPERTY_NAME = '_style'

    __slots__ = [
        'sheet',
        'values'
    ]

    def __init__(self, file: str, sheet_name: str):
        super().__init__(file)
        self.sheet = super().get_sheet(sheet_name)
        self.__print_excel_file_info(file, sheet_name)
        self.values = list(self.sheet.values)

    def __print_excel_file_info(self, filename: str, sheet_name: str) -> None:
        print('Excel处理文件<%s>解析完成' % filename)
        print('Sheet<%s>共有数据 %d 行 %d 列' % (sheet_name, self.sheet.max_row, self.sheet.max_column))

    def fill_column_values(self, *,
                           column_dimension: str,
                           data_row_number: int,
                           handler: CellDataHandler) -> None:
        self.fill_conditional_column_values(column_dimension=column_dimension,
                                            data_row_number=data_row_number,
                                            condition=None,
                                            handler=handler)

    def fill_conditional_column_values(self, *,
                                       column_dimension: str,
                                       data_row_number: int,
                                       condition: Condition or None,
                                       handler: CellDataHandler) -> None:
        style_array = getattr(self.sheet.column_dimensions[column_dimension], self.__STYLE_PROPERTY_NAME)
        for i in range(data_row_number, self.sheet.max_row + 1):
            if condition is not None and not condition.affirm(self.values[i - 1]):
                continue
            self.sheet[column_dimension + str(i)] = handler.handle(self.values[i - 1])
            setattr(self.sheet[column_dimension + str(i)], self.__STYLE_PROPERTY_NAME, style_array)
        print('<%s>列数据填充完毕' % column_dimension)
